//
//  DanmakuViewModel.swift
//  live
//
//  Created by melvyn on 2018/8/19.
//  Copyright © 2018 NEET. All rights reserved.
//

import Foundation
import Differentiator
import RxSwift
import RxCocoa
import struct Link.Comment

typealias DanmakuTable = AnimatableSectionModel<String, DanmakuViewModel>
final class DanmakuListViewModel: RxViewModel {
    
    var sections: Driver<[DanmakuTable]>
    var disposeBag = DisposeBag()
    
    init(danmakus: Observable<[Comment]>) {
        
        var models: [DanmakuViewModel] = []
        
        sections = danmakus
            .map {
                $0.forEach({
                    if !models.map({ $0.danmaku! }).contains($0)  {
                        models.append(DanmakuViewModel.init(danmaku: $0))
                    }
                })
                return models
            }
            .map {
                [DanmakuTable.init(model: "", items: $0)]
            }
            .asDriver(onErrorJustReturn: [])
    }
}


class DanmakuViewModel {
    let danmaku: Comment!
    
    let nickname: Driver<String?>
    let uLv: Driver<String>
    let content: Driver<String?>
    let title: Driver<String?>
    
    init(danmaku: Comment) {
        self.danmaku = danmaku
        let relay = BehaviorRelay.init(value: danmaku)
        
        nickname = relay.asDriver()
            .map({ $0.user?.nickname })
        
        uLv = relay.asDriver()
            .map({ "UL \($0.user?.level ?? 0)" })
        
        content = relay.asDriver()
            .map({ $0.content })
        
        title = relay.asDriver()
            .map({ _ in nil })
    }
}

extension DanmakuViewModel: IdentifiableType, Equatable {
    var identity: Int {
        return danmaku.id
    }
    
    public static func == (lhs: DanmakuViewModel, rhs: DanmakuViewModel) -> Bool {
        return lhs.danmaku.id == rhs.danmaku.id
    }
}
